package org.neurone.userspace.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.neurone.domain.Application;
import org.neurone.domain.persistence.ApplicationPersistence;
import org.neurone.userspace.dao.ApplicationDao;
import org.neurone.util.criteria.Criteria;
import org.springframework.orm.hibernate3.HibernateCallback;

public class ApplicationDaoImpl extends BaseDaoHibernate implements
		ApplicationDao {

	@Override
	public void delete(Long applicationID) {
		ApplicationPersistence ap = (ApplicationPersistence)find(applicationID);
		getHibernateTemplate().delete(ap);
	}

	@Override
	public Application find(Long applicationID) {

		return (ApplicationPersistence)getHibernateTemplate().load(ApplicationPersistence.class, applicationID);
	}

	@Override
	public Long newApplication(Application application) {
		ApplicationPersistence ap = new ApplicationPersistence();
		ap = fillApplication(application, ap);
		getHibernateTemplate().saveOrUpdate(ap);
		return ap.getApplicationID();
	}

	@Override
	public List<Application> search(final Criteria terms, int pageSize, int pageIndex) {
		List<Application> list = getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session session)
			throws HibernateException, SQLException {
				String termString = "";
				if(terms != null)
				{
					termString = " where "+terms.getSQLCriteria();
				}
				
				Query query = session.createQuery("from ApplicationPersistence as applicationPersistence "+termString );
				//query.setFirstResult(pageSize *pageIndex);
				//query.setMaxResults(pageSize);
				List<Application> list = query.list();
				return list;
			}
		});
		return list;
	}

	@Override
	public void update(Application application) {
		ApplicationPersistence ap = (ApplicationPersistence)find(application.getApplicationID());
		if(ap != null)
		{
			ap = fillApplication(application, ap);
			getHibernateTemplate().update(ap);
		}
	}

	private ApplicationPersistence fillApplication(Application source, ApplicationPersistence ap)
	{
		ap.setApplicationDescription(source.getApplicationDescription());
		ap.setApplicationKey(source.getApplicationKey());
		ap.setApplicationName(source.getApplicationName());
		ap.setApplicationType(source.getApplicationType());
		ap.setCallbackUrl(source.getCallbackUrl());
		ap.setIcon(source.getIcon());
		ap.setPluginType(source.getPluginType());
		ap.setServerIP(source.getServerIP());
		ap.setTags(source.getTags());
		ap.setVisibleLevelKey(source.getVisibleLevelKey());
		
		return ap;
	}
}
